package org.hades.corelib.utils.device

import android.content.Context
import android.graphics.Rect
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.View
import android.view.WindowManager
import org.hades.corelib.utils.AppUtils.app


object SizeHelper {
    /**
     * transform dip to px
     *
     * @param dipValue the value of dip
     * @return px
     */
    fun dip2px(dipValue: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dipValue,
            app!!.resources.displayMetrics
        )
    }

    /**
     * transform sp to px
     *
     * @param spValue spValue
     * @return px
     */
    fun sp2px(spValue: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spValue,
            app!!.resources.displayMetrics
        )
    }

    /**
     * get this view location on screen
     *
     * @param view view
     * @return rect
     */
    fun getRectOnScreen(view: View): Rect {
        val location = getLocationOnScreen(view)
        val left = location[0]
        val top = location[1]
        val right: Int = left + view.measuredWidth
        val bottom: Int = top + view.measuredHeight
        return Rect(left, top, right, bottom)
    }

    /**
     * get this view position on screen
     *
     * @param view view
     * @return int[]
     */
    fun getLocationOnScreen(view: View): IntArray {
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        return location
    }

    /**
     * get device screen size
     * @return DisplayMetrics
     */
    val screenSize: DisplayMetrics
        get() {
            val context: Context? = app
            val wm: WindowManager =
                context?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val metrics = DisplayMetrics()
            wm.defaultDisplay.getMetrics(metrics)
            return metrics
        }
}
